package com.mask.im.business.controller;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.mask.im.business.common.model.RestResponse;
import com.mask.im.business.common.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author jian
 */
@Api(tags = "oss文件上传模块")
@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    @Value("${spring.cloud.alicloud.secret-key}")
    private String accessKey;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

//    @Value("${spring.tengxun.accessKey}")
//    private String accessKey;
//    @Value("${spring.tengxun.secretKey}")
//    private String secretKey;
//    @Value("${spring.tengxun.bucket}")
//    private String bucket;
//    @Value("${spring.tengxun.bucketName}")
//    private String bucketName;
//    @Value("${spring.tengxun.path}")
//    private String path;
//    @Value("${spring.tengxun.qianzui}")
//    private String qianzui;
//
//    /**
//     * 上传道腾讯云服务器（https://cloud.tencent.com/document/product/436/10199）
//     * @return
//     */
//    @RequestMapping(value = "/tengxun",method = RequestMethod.POST)
//    @ResponseBody
//    public RestResponse Upload(@RequestParam(value = "file") MultipartFile file){
//        if(file == null){
//            return  RestResponse.fail(0,"文件为空");
//        }
//        String oldFileName = file.getOriginalFilename();
//        String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
//        String newFileName = UUID.randomUUID()+eName;
//        Calendar cal = Calendar.getInstance();
//        int year = cal.get(Calendar.YEAR);
//        int month=cal.get(Calendar.MONTH);
//        int day=cal.get(Calendar.DATE);
//        // 1 初始化用户身份信息(secretId, secretKey)
//        COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
//        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
//        ClientConfig clientConfig = new ClientConfig(new Region(bucket));
//        // 3 生成cos客户端
//        COSClient cosclient = new COSClient(cred, clientConfig);
//        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
//        String bucketName = this.bucketName;
//
//        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
//        // 大文件上传请参照 API 文档高级 API 上传
//        File localFile = null;
//        try {
//            localFile = File.createTempFile("temp",null);
//            file.transferTo(localFile);
//            // 指定要上传到 COS 上的路径
//            String key = "/"+this.qianzui+"/"+year+"/"+month+"/"+day+"/"+newFileName;
//            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
//            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
//            return  RestResponse.ok(this.path + putObjectRequest.getKey());
//        } catch (IOException e) {
//            return  RestResponse.fail(-1,e.getMessage());
//        }finally {
//            // 关闭客户端(关闭后台线程)
//            cosclient.shutdown();
//        }
//    }


    @ApiOperation("oss文件上传")
    @PostMapping("/oss")
    public RestResponse<?> ossFileUploadContext(@RequestPart("file") MultipartFile file) {
        String url = null;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        try {
            InputStream inputStream = file.getInputStream();
            String md5 = FileUtil.getMd5(file.getInputStream());
            String extName = FileUtil.getExtName(file.getOriginalFilename());
            //获取上传的文件的名字
            String filename = md5+extName;
            //随机uuid是为了拼接文件名，防止用户上传两个名字相同的文件后覆盖掉前一个
            UUID uuid = UUID.randomUUID();
            //这里是为了按上传时间分配目录。精确到月
            String s = DateTime.now().toString("yyyy/MM/");
            //拼接成完整的文件名。
            filename = s + uuid + filename;
            //传入三个参数
            ossClient.putObject(bucket, filename, inputStream);
            //拼接url
            url = "https://" + bucket + "." + endpoint + "/" + filename;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return RestResponse.okData(url);
    }


    @ApiOperation("oss文件上传")
    @PostMapping("/voice")
    public RestResponse<?> voice(@RequestParam("file") MultipartFile file,
                                 @RequestParam("duration") int duration) throws IOException {
        // 创建保存目录
        File dir = new File("/Users/jian/Desktop/registry/");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + extension;
        // 保存文件
        File dest = new File("/Users/jian/Desktop/registry/" + fileName);
        file.transferTo(dest);
        // 返回结果
        return RestResponse.okData("/Users/jian/Desktop/registry/" + fileName);
    }


    @ApiOperation("oss文件上传")
    @PostMapping("/image")
    public RestResponse<?> image(@RequestParam("file") MultipartFile file,
                                 @RequestParam("type") int type) throws IOException {
        // 创建保存目录
        File dir = new File("/Users/jian/Desktop/registry/");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + extension;
        // 保存文件
        File dest = new File("/Users/jian/Desktop/registry/" + fileName);
        file.transferTo(dest);
        long size = file.getSize();
        // 返回结果
        return RestResponse.okData("/Users/jian/Desktop/registry/" + fileName);
    }
}
